<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数码时钟</title>
  <style>
    .container {
      width: 500px;
      margin: 200px auto 0;
      text-align: center;
    }

    .container img {
      width: 50px;
      height: 74px;
      vertical-align: middle;
    }

    .container span {
      font-size: 18px;
      font-weight: 700;
    }
  </style>
</head>

<body>
  <div class="container">
    <img src="" alt="" class="hour">
    <img src="" alt="" class="hour">
    <span>时</span>
    <img src="" alt="" class="minute">
    <img src="" alt="" class="minute">
    <span>分</span>
    <img src="" alt="" class="second">
    <img src="" alt="" class="second">
    <span>秒</span>
  </div>

  <script>
    // 获取图片元素
    const hourImgs = document.querySelectorAll('.hour');
    const minuteImgs = document.querySelectorAll('.minute');
    const secondImgs = document.querySelectorAll('.second');

    // numImgs数组中每个元素的索引号与其图片路径所显示的数字是相同的
    let numImgs = ['./img/0.png', './img/1.png', './img/2.png', './img/3.png', './img/4.png', './img/5.png',
      './img/6.png', './img/7.png', './img/8.png', './img/9.png'
    ];

    setInterval(getCurrentTime, 1000); // 每间隔1秒，就更新一次时间

    getCurrentTime(); // 首屏加载

    // 获取当前时间函数
    function getCurrentTime() {
      let now = new Date();
      let hours = now.getHours(); // 时
      hours = hours < 10 ? '0' + hours : hours;
      let minutes = now.getMinutes(); // 分
      minutes = minutes < 10 ? '0' + minutes : minutes;
      let seconds = now.getSeconds(); // 秒
      seconds = seconds < 10 ? '0' + seconds : seconds;
      // console.log(hours + ':' + minutes + ':' + seconds);
      // 分别调用图片切换函数，一一对应
      toggleImg(hours, hourImgs);
      toggleImg(minutes, minuteImgs);
      toggleImg(seconds, secondImgs);
    }

    // 封装图片切换函数
    function toggleImg(time, img) {
      // 因为 hours, minutes, seconds 均有可能为 Number类型 或是 String类型
      // 所以先将它们都转换成 String类型，再通过 split() 变为数组，最后遍历数组
      time.toString().split('').forEach((item, index) => {
        // 注意：item 是当前时间内的单个数字(0-9)，用numImg数组中的图片替代
        img[index].src = numImgs[item]; // 给img标签添加上对应的src属性值
      });
    }
  </script>
</body>

</html>